<template>
  <div class="about">
    <!-- 当 id 存在时 为编辑 否则是 新建 -->
    <h1>{{id ? "编辑" : "新建"}}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <el-select v-model="model.parent">
          <el-option v-for="item in parents" :key="item._id" 
          :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  // 获取路由里传过来的 需要编辑的 分类的 id
  props: {
    id: {}
  },
  data() {
    return {
      model: {
        name: ""
      },
      parents: []
    };
  },
  created() {
    //   当 id 存在时 触发 fetch 函数
    this.fetchParents()
    this.id && this.fetch();
  },
  methods: {
    fetchParents(){
      this.$http.get("/rest/categories").then(res => {
        this.parents = res.data;
        console.log(res)
      });
    },
    fetch() {
      this.$http.get(`/rest/categories/${this.id}`).then(res => {
        this.model = res.data;
        console.log(res);
      });
    },
    save() {
      // 如果 id 存在 则为修改  否则为新建
      this.$http.put(`/rest/categories/${this.id}`, this.model).then(res => {
        console.log(res);
        this.$router.push("/categoires/list");
        this.$message({
          showClose: true,
          message: "恭喜你，修改成功",
          type: "success"
        });
      });
    }
  }
};
</script>

<style lang='css' scoped>
</style>